﻿Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Configuration
Imports System.Xml
Imports System.Net
Imports System.Collections
Imports System.Collections.Generic
Imports System.IO
Imports System.Data

Partial Class NeatUpload
    Inherits System.Web.UI.Page
    Dim sharePointListPath As String = ConfigurationManager.AppSettings("SharePointServer")
    Dim lock As Boolean
    Public scripttext As String
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        AddHandler SaveDocument.Click, AddressOf Me.SaveDocument_Click

        Dim EformID As Decimal
        EformID = Val(Request("BDID"))
        Dim adap As New FormLockDSTableAdapters.BudgetDetailsTableAdapter
        Dim dt As New FormLockDS.BudgetDetailsDataTable
        dt = adap.GetData(EformID)
        If dt.Count > 0 Then
            Dim re_adap As New FormLockDSTableAdapters.FundCenterReleasesTableAdapter
            Dim count As Integer = re_adap.CountRelease(dt.Item(0).PlanYear, dt.Item(0).Version, dt.Item(0).FundCenter_FundCenterCode)
            If count > 0 Then
                DocumentFile.Enabled = False
                SaveDocument.Enabled = False
                Lock = True
            End If

            'Add By Orn 5/12/2557
            If dt.Item(0).IsActivityType_ActivityTypeCodeNull Then
                hddCmmtCode.Value = dt.Item(0).Cmmt_CmmtCode
                hddPlanYear.Value = dt.Item(0).Cmmt_PlanYear
                'Add by Orn 27/06/2558
                If Title.Text = "" Then
                    Dim actDT As New MasterDataSet2TableAdapters.CmmtsTableAdapter
                    Dim dtTable As New MasterDataSet2.CmmtsDataTable
                    Dim sql As String = "select * from Cmmts "
                    sql += " WHERE CmmtCode =  '" & hddCmmtCode.Value & "' "
                    sql += " AND PlanYear =  '" & hddPlanYear.Value & "' "
                    actDT.SearchCmmts(dtTable, sql)
                    If dtTable.Rows.Count > 0 Then
                        Title.Text = dtTable.Rows(0)("FileNamePattern").ToString()
                    End If
                End If
            Else
                hddActivityTypeCode.Value = dt.Item(0).ActivityType_ActivityTypeCode
                hddPlanYear.Value = dt.Item(0).ActivityType_PlanYear
                'Add by Orn 27/06/2558
                If Title.Text = "" Then
                    Dim actDT As New ActTypeDS.ActivityTypesDataTable
                    Dim actAdap As New ActTypeDSTableAdapters.ActivityTypesTableAdapter
                    actDT = actAdap.GetDataByCode(hddActivityTypeCode.Value, hddPlanYear.Value)
                    If actDT.Rows.Count > 0 Then
                        If Not actDT.Item(0).IsFileNamePatternNull Then
                            Title.Text = actDT.Item(0).FileNamePattern
                        End If
                    End If
                End If
            End If
            'End Add By Orn 5/12/2557
        End If

        BindGridViewData()
    End Sub

    Protected Sub SaveDocument_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim saveDir As String = "\Uploaded\"
        Dim appPath As String = Request.PhysicalApplicationPath

        If (DocumentFile.HasFile) Then
            'Add By Orn 5/12/2557
            If hddActivityTypeCode.Value <> "" Then
                Dim actDT As New ActTypeDS.ActivityTypesDataTable
                Dim actAdap As New ActTypeDSTableAdapters.ActivityTypesTableAdapter
                actDT = actAdap.GetDataByCode(hddActivityTypeCode.Value, hddPlanYear.Value)
                If actDT.Rows.Count > 0 Then
                    Try
                        If actDT.Item(0).TemplateName <> "" Then
                            Dim fileupload As String = DocumentFile.FileName.Substring(0, DocumentFile.FileName.LastIndexOf("."))
                            Dim tmname As String = actDT.Item(0).TemplateName.Substring(0, actDT.Item(0).TemplateName.LastIndexOf("."))
                            If fileupload.IndexOf(tmname) < 0 Then
                                scripttext = "<script>alert('ชื่อไฟล์ไม่ตรงกับ " & tmname & " กรุณาเปลี่ยนชื่อใหม่');</script>"
                                Exit Sub
                            End If
                        End If
                    Catch ex As Exception

                    End Try
                End If
            Else
                Dim actDT As New MasterDataSet2TableAdapters.CmmtsTableAdapter
                Dim dtTable As New MasterDataSet2.CmmtsDataTable
                Dim sql As String = "select * from Cmmts "
                sql += " WHERE CmmtCode =  '" & hddCmmtCode.Value & "' "
                sql += " AND PlanYear =  '" & hddPlanYear.Value & "' "
                actDT.SearchCmmts(dtTable, sql)
                If dtTable.Rows.Count > 0 Then
                    Try
                        If dtTable.Rows(0)("FileNamePattern").ToString() <> "" Then
                            Dim fileupload As String = DocumentFile.FileName.Substring(0, DocumentFile.FileName.LastIndexOf("."))
                            Dim tmname As String = dtTable.Rows(0)("TemplateName").ToString().Substring(0, dtTable.Rows(0)("TemplateName").ToString().LastIndexOf("."))
                            If fileupload.IndexOf(tmname) < 0 Then
                                scripttext = "<script>alert('ชื่อไฟล์ไม่ตรงกับ " & tmname & " กรุณาเปลี่ยนชื่อใหม่');</script>"
                                Exit Sub
                            End If
                        End If
                    Catch ex As Exception

                    End Try
                End If
            End If
            'End Add By Orn 5/12/2557

            'Dim extension As String = System.IO.Path.GetExtension(DocumentFile.PostedFile.FileName)
            'Dim fileName As String = Server.HtmlEncode(DocumentFile.FileName)
            Dim extension As String = System.IO.Path.GetExtension(DocumentFile.FileName)
            Dim fileName As String = GenerateFileName("yyyyMMddhhmmss") & "-" & Session("users") & extension

            'Dim extension As String = System.IO.Path.GetExtension(fileName)
            'If (extension = ".doc") Or (extension = ".xls") Then
            'End If

            Dim fileSize As Integer = DocumentFile.ContentLength
            Dim mimeType As String = DocumentFile.ContentType

            If (fileSize > 5242880) Then
                filelimit.Visible = True
                Exit Sub
            Else
                filelimit.Visible = False
            End If

            Dim savePath As String = appPath + saveDir + fileName
            'Try
            'Response.Write("x" & Server.MapPath("~\project_document\") & fileName & "y")
            DocumentFile.MoveTo(Server.MapPath("~\Uploaded\") & fileName, Brettle.Web.NeatUpload.MoveToOptions.Overwrite)
            'Catch Exc As Exception
            'End Try

            'UploadSharepoint(fileName, Server.MapPath("~\Uploaded\"))

            'Dim sharePointListPath As String = "http://win-mudl4fhr3s1/DocumentBB/Documents/"

            '''' Start Sharepoint Upload
            UploadFileToSharePoint(Server.MapPath("~\Uploaded\") & fileName, sharePointListPath + fileName)

            Try
                File.Delete(Server.MapPath("~\Uploaded\") & fileName)
            Catch ex As Exception

            End Try
            '''' End Sharepoint Upload

            Dim mySelectQuery As String
            Dim ProjectID As String
            Dim EformID As Decimal
            EformID = Val(Request("BDID"))
            Dim adapter As New AttachmentTableAdapters.AttachmentsTableAdapter
            Dim adapter2 As New AttachmentTableAdapters.BudgetDetailsTableAdapter
            Dim item_no As Integer
            item_no = adapter.GetMaxItemNo(EformID)
            adapter.InsertAttachment(item_no, fileName, extension, fileSize, mimeType, Now(), Nothing, Session("usr_id"), Nothing, EformID, 0, Title.Text)
            Dim currentAmount As Decimal = adapter.GetAttAmount(EformID)
            adapter2.UpdateAttAmount(currentAmount, EformID)
            BindGridViewData()
            If Request("fid") = "f05" Then
                scripttext = "<script>F05_close(" & currentAmount & "," & Request("rownum") & ");</script>"
            End If
        End If
    End Sub
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        Dim RunningNo As Label = e.Row.Cells(0).FindControl("RunningNo")
        If Not (RunningNo Is Nothing) Then
            RunningNo.Text = e.Row.RowIndex + 1
        End If

        If lock = True Then
            e.Row.Cells(e.Row.Cells.Count - 1).Text = ""
        End If
    End Sub

    Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
        GridView1.PageIndex = e.NewPageIndex
        GridView1.EditIndex = -1
        BindGridViewData()
    End Sub
    Protected Sub DeleteDocument_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim ConfirmResult As Boolean = ConfirmBox.Value
        If ConfirmResult = False Then
            Exit Sub
        End If

        Dim Row As System.Web.UI.WebControls.GridViewRow
        Row = sender.Parent.Parent
        Dim IDX As Label = Row.Cells(3).FindControl("ProjectDocumentID")
        Dim adapter As New AttachmentTableAdapters.AttachmentsTableAdapter
        Dim adapter2 As New AttachmentTableAdapters.BudgetDetailsTableAdapter

        adapter.DeleteAttachment(Val(IDX.Text))
        Dim filename As Label = Row.Cells(3).FindControl("Filename")
        Dim countfile As Integer = 0
        countfile = adapter.CountExistFile(filename.Text.Trim)

        Dim currentAmount As Decimal = adapter.GetAttAmount(Val(Request("BDID")))

        adapter2.UpdateAttAmount(currentAmount, Val(Request("BDID")))
        If Request("fid") = "f05" Then
            scripttext = "<script>F05_close(" & currentAmount & "," & Request("rownum") & ");</script>"
        End If
        BindGridViewData()

        If filename.Text.Trim <> "" And countfile <= 1 Then
            DeleteFileSP(sharePointListPath & filename.Text.Trim)
        End If

    End Sub
    Sub BindGridViewData()
        Dim adapter As New AttachmentTableAdapters.AttachmentsTableAdapter
        Dim data As New Attachment.AttachmentsDataTable
        data = adapter.GetDataByRefID(Val(Request("BDID")))
        GridView1.DataSource = data
        GridView1.DataBind()
    End Sub
    Public Function GenerateOnClick(ByVal data As String, ByVal name As String) As String
        Return "window.open('DownloadFile.aspx?filepath=" & data & "&filename=" & name & "','view_document','menubar=0,resizable=1,width=800,height=600');"
    End Function
    Public Shared Function GenerateFileName(ByVal data As String) As String
        Return Now().ToString(data)
    End Function

    Sub UploadFileToSharePoint(ByVal UploadedFilePath As String, ByVal SharePointPath As String)

        Dim resp As WebResponse = Nothing

        Try
            ' Create a PUT Web request to upload the file.
            Dim request As WebRequest = WebRequest.Create(SharePointPath)
            'Dim mycache As New CredentialCache
            'mycache.Add(New Uri(SharePointPath), "Windows", New NetworkCredential("WIN-MUDL4FHR3S1\Administrator", "Secret1"))
            request.Credentials = CredentialCache.DefaultCredentials
            request.Method = "PUT"

            ' Allocate a 1 KB buffer to transfer the file contents.
            ' You can adjust the buffer size as needed, depending on
            ' the number and size of files being uploaded.
            Dim buffer() As Byte = New Byte(1023) {}

            ' Write the contents of the local file to the
            ' request stream.
            Using stream As Stream = request.GetRequestStream()
                Using fsWorkbook As FileStream = _
                    File.Open(UploadedFilePath, _
                        FileMode.Open, FileAccess.Read)
                    Dim i As Integer = fsWorkbook.Read(buffer, 0, _
                        buffer.Length)

                    Do While i > 0
                        stream.Write(buffer, 0, i)
                        i = fsWorkbook.Read(buffer, 0, buffer.Length)
                    Loop

                End Using
            End Using

            ' Make the PUT request.

            'Response.Write(resp.ResponseUri.AbsolutePath.ToString())
            resp = request.GetResponse()

        Catch ex As Exception
            Throw ex
        Finally
            'Response.Write(resp.ResponseUri.AbsolutePath.ToString())
            'resp.Close()
        End Try

    End Sub

    Sub DeleteFileSP(ByVal SharePointPath As String)
        Dim resp As WebResponse = Nothing

        Dim request As WebRequest = WebRequest.Create(SharePointPath)
        request.Credentials = CredentialCache.DefaultCredentials
        request.Method = "DELETE"
        resp = request.GetResponse()
    End Sub
End Class
